<template>
	<view class="container">

		<uni-segmented-control :current="currentIndex" :values="items" style-type="text" active-color="#007aff"
			@clickItem="onClickItem" />

		<view v-if="currentIndex === 0">
			<view style="padding-top: 10px;"></view>
			<uni-forms ref="baseForm" :modelValue="bukaApplyForm" labelPosition="left" border labelWidth="100px">
				<view style="padding-top: 10px;"></view>

				<uni-forms-item label="日期">
					<view class="text-bg">{{getFormatedTimeStr(day,'YYYY-MM-DD')}}</view>
				</uni-forms-item>
				<uni-forms-item label="补卡类型">
					<view class="text-bg">{{bukaType == 1 ? '上班卡' : '下班卡'}}</view>
				</uni-forms-item>
				<uni-forms-item label="原因">
					<uni-easyinput type="textarea"  @change="chuanci2" @input="chuanci2"  v-model="bukaApplyForm.reason" />
				</uni-forms-item>
				
				<!-- 图片上传模块 -->
				<uni-forms-item label="相关证明"></uni-forms-item>
				<uni-row>
					<uni-col :span="8" v-for="(item, idx) in bukaApplyForm.pics">
						<view class="img-res" @click="showBigImg(bukaApplyForm.pics,idx)">
							<image :src="bukaApplyForm.pics[idx]" :key="idx" />
						</view>
					</uni-col>
				</uni-row>
				<button @click="clickSelectPic" class="btn-add">选择图片</button>


				<!-- 选人模块 -->
				<uni-forms-item label="审核人" required></uni-forms-item>
				<view v-for="(item, idx) in bukaApplyForm.auditors">
					<uni-row>
						<uni-col :span="10">
							<view v-if="idx>0" class="step-arrow">
								<uni-icons type="bottom" size="mini" color='#a5eaff'></uni-icons>
							</view>
						</uni-col>
					</uni-row>
				
					<view class="step">
						<uni-row>
							<uni-col :span="10">
								<view class="step-info-left">{{item.stepName || item.positionName}}</view>
							</uni-col>
							<uni-col :span="14">
								<view class="step-info-right">{{item.name}}</view>
							</uni-col>
						</uni-row>
					</view>
				</view>


				<view style="padding-top: 50px;"></view>
				<button type="primary" @click="clickApply">提交</button>
			</uni-forms>
		</view>

		<view v-if="currentIndex === 1">
			<view v-for="(item, idx) in applyRecord" style="padding-bottom: 10px;">
				<view class="card" @click="seeDetail(idx)">
					<view class="card-title">
						<uni-row>
							<uni-col :span="20">
								<view class="card-title-left">{{getFormatedTimeStr(item.day,'YYYY-MM-DD')}}</view>
							</uni-col>
							<uni-col :span="4">
								<view class="card-title-right">
									<uni-tag text="审核" size="mini" type="warning" v-if="item.sta===0&&item.chexiao==0"></uni-tag>
									<uni-tag text="通过" size="mini" type="primary" v-if="item.sta===1&&item.chexiao==0"></uni-tag>
									<uni-tag text="拒绝" size="mini" type="error" v-if="item.sta===2&&item.chexiao==0"></uni-tag>
									<uni-tag text="撤销" size="mini" type="default" v-if="item.chexiao===1"></uni-tag>
								</view>
							</uni-col>
						</uni-row>
					</view>
					<view class="card-body">
						<view>类型：{{item.bukaType == 1 ? '上班卡' : '下班卡'}}</view>
						<view>原因：{{item.reason}}</view>
					</view>
					<view class="card-footer">
						<uni-row>
							<uni-col :span="24">
								<view class="card-footer-right">
									{{getFormatedTimeStr(item.createTime)}}
								</view>
							</uni-col>
						</uni-row>
					</view>
				</view>
			</view>

			<uni-load-more :status="moreStatus"></uni-load-more>
		</view>
	</view>
</template>

<script>
	import moment from 'moment'
	import {
		websock
	} from '../../net/websock'
	import {uploadconfig} from '../../const'
	import { quchongAuditors } from '../../utils/util'

	export default {
		data() {
			return {
				uploadconfig,
				items: ['发起提交', '查看数据'],

				departNames: [],
				departIds: [],
				departIndex: 0,

				currentIndex: 0,

				moreStatus: 'more',
				applyRecord: [],
				day: '',
				bukaType: '',
				id: 0,
				bukaApplyForm: {
					reason: '',
					pics: [],
					auditors: []
				}
			}
		},
		onLoad(params) {
			this.day = params.day || ''
			this.bukaType = params.bukaType
			this.id = params.id
		},
		async onReady() {

			let departList = await websock.getDepartList()
			for (let i = 0; i != departList.length; i++) {
				this.departNames.push(departList[i].name)
				this.departIds.push(departList[i].id)
			}

			let auditors = await websock.getAuditors({typ: 19})
			console.log('auditors', auditors)
			quchongAuditors(auditors)
			this.bukaApplyForm.auditors = auditors

			this.getNewestRecord()
		},
		// 下拉刷新，获取最新的数据
		onPullDownRefresh() {
			console.log('onPullDownRefresh')
			if (this.currentIndex == 0) {
				uni.stopPullDownRefresh()
			} else {
				this.getNewestRecord()
			}
		},
		// 上拉刷新，获取历史数据
		onReachBottom() {
			console.log('onReachBottom')
			if (this.currentIndex == 1) {
				this.getOlderRecord()
			}
		},
		methods: {
			departChange(e) {
				console.log('depart change', e.detail.value)
				this.departIndex = e.detail.value
			},
			departNameStr() {
				return this.departNames[this.departIndex] || ''
			},
			// 获取最新的通知
			async getNewestRecord() {
				try {
					if (this.applyRecord.length == 0) {
						let res = await websock.bukaApplyRecord({
							pageCount: 10
						})
						console.log('getRecordList list empty', res)
						uni.stopPullDownRefresh()
						this.applyRecord = [...res, ...this.applyRecord]
					} else {
						let res = await websock.bukaApplyRecord({
							greaterThan: this.applyRecord[0].id,
							pageCount: 10
						})
						console.log('getRecordList list not empty', res)
						uni.stopPullDownRefresh()
						this.applyRecord = [...res, ...this.applyRecord]
					}
				} catch (e) {
					uni.showToast({
						title: e.message
					})
				}
			},
			// 获取老的数据
			async getOlderRecord() {
				this.moreStatus = 'loading'
				try {
					if (this.applyRecord.length == 0) {
						console.log('before get list empty')
						let res = await websock.bukaApplyRecord({
							pageCount: 10
						})
						console.log('getOlderRecord list empty', res)
						this.applyRecord = [...this.applyRecord, ...res]
						if (res.length < 10) {
							this.moreStatus = 'noMore'
						} else {
							this.moreStatus = 'more'
						}
					} else {
						console.log('before get list not empty')
						let res = await websock.bukaApplyRecord({
							lessThan: this.applyRecord[this.applyRecord.length - 1].id,
							pageCount: 10
						})
						console.log('getOlderRecord list not empty', res)
						this.applyRecord = [...this.applyRecord, ...res]
						if (res.length < 10) {
							this.moreStatus = 'noMore'
						} else {
							this.moreStatus = 'more'
						}
					}
				} catch (e) {
					uni.showToast({
						title: e.message
					})
				}
			},
			onuploadEnd(item) {
				console.log(`${item.name}已上传结束，上传状态=${item.type}`);

				if (item.type == 'fail') {
					return uni.showToast({
						title: '上传失败'
					})
				}

				try {
					let res = JSON.parse(item.responseText)

					if (res.code !== 0) {
						return uni.showToast({
							title: res.message || 'error'
						})
					}

					this.bukaApplyForm.attaches.push({
						name: item.name,
						path: res.data
					})
				} catch (err) {
					uni.showToast({
						title: err.message
					})
				}
			},
			onClickItem(e) {
				if (this.currentIndex !== e.currentIndex) {
					this.currentIndex = e.currentIndex
				}
			},
			
			clickSelectAuditor() {
				uni.navigateTo({
					url: '/pages/common/contactSelect?selectedUsers=' + JSON.stringify(this.bukaApplyForm.auditors || []),
					events: {
						contactList: data => {
							console.log('select auditor', data)
							this.bukaApplyForm.auditors = data.contactList
						}
					}
				})
			},
			
			// 获取格式化时间字符串
			getFormatedTimeStr(stamp, str='MM-DD HH:mm:ss') {
				return moment(stamp).format(str)
			},
			async clickApply() {

				console.log('click buka apply', this.bukaApplyForm)

				if (!this.bukaApplyForm.reason) return uni.showToast({
					title: '请输入补卡原因',icon:'none'
				})

				if (this.bukaApplyForm.auditors.length == 0) return uni.showToast({
					title: '请选择审核人',icon:'none'
				})

				let auditors = []
				for (let i = 0; i != this.bukaApplyForm.auditors.length; i++) {
					auditors.push({uid: this.bukaApplyForm.auditors[i].uid, stepName: this.bukaApplyForm.auditors[i].stepName || this.bukaApplyForm.auditors[i].positionName})
				}

				try {
					await websock.bukaApply({
						department: this.departNames[this.departIndex],
						day: this.day,
						bukaType: this.bukaType,
						id: this.id,
						reason: this.bukaApplyForm.reason,
						pics: this.bukaApplyForm.pics,
						auditors
					})

					uni.showToast({
						title: '申请成功'
					})

					this.bukaApplyForm = {
						reason: '',
						pics: [],
						auditors: []
					}

					this.currentIndex = 1
					this.getNewestRecord()
				} catch (err) {
					uni.showToast({
						title: err.message || 'error'
					})
				}
			},
			// 选择图片
			clickSelectPic() {
				uni.chooseImage({
					count: 9, //选择图片数
					sourceType: ['camera', 'album'], //从相册还是相机选择
					success: (res) => {
						for (let path in res.tempFilePaths) {
							uni.uploadFile({
								url: this.uploadconfig.url,
								filePath: res.tempFilePaths[path],
								name: 'file',
								formData: {
								},
								success: res => {
									try {
										let data = JSON.parse(res.data)
										if (data.code != 0) {
											return uni.showToast({
												title: data.message
											})
										}
										this.bukaApplyForm.pics.push(data.data)
									} catch (e) {
										console.error(e)
										uni.showToast({
											title: '上传图片失败' + e.message,icon:'none'
										})
									}
									console.log('success', res)
								},
								fail: (res) => {
									uni.showToast({
										title: '上传图片失败' + res,icon:'none'
									})
								},
								complete: () => {
									console.log('uploa file complete')
								}
							})
						}
			
					}
				})
			},
			//点击放大图片
			showBigImg(imgurl, cur) {
				uni.previewImage({
					current: cur,
					loop: true,
					urls: imgurl,
				})
			},
			seeDetail(idx) {
				uni.navigateTo({
					url: `/pages/task/bukaApplyDetail?id=${this.applyRecord[idx].id}`
				})
			}
		}
	}
</script>

<style>
	@import '../common/common.css';
</style>
